package com.why.oss.service.iml;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.why.oss.service.ossService;
import com.why.oss.uitls.ConstantPropertiesUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Path;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

/**
 * @program: guli_parent
 * @description:
 * @author: @why
 * @create: 2021-01-30 11:56
 **/
@Service
public class ossServiceIml implements ossService {

    @Override
    public String uploadAvatar(MultipartFile fileStream) {
        //  地域节点
        String endpoint = ConstantPropertiesUtils.END_POINT;
        // 访问用户名和密码
        String accessKeyId = ConstantPropertiesUtils.ACCESS_KEY_ID;
        String accessKeySecret = ConstantPropertiesUtils.ACCESS_KEY_SECRET;
        String BucketName=ConstantPropertiesUtils.BUCKET_NAME;
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        //得到上传的文件的名字
        String filename = fileStream.getOriginalFilename();
        String uuId = UUID.randomUUID().toString().replaceAll("-", "");
        //防止文件命名重复
        filename=uuId+filename;
        // 上传文件流搞里头
        InputStream inputStream = null;
        try {
            inputStream = fileStream.getInputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }

        Date todayDate = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM");
        String pathName = dateFormat.format(todayDate)+"/"+filename;

        //上传的参数，一个是桶的名字
        //一个是我们上传到oss文件路径和文件名称
        //此时我们再将fileName拼接上路径名字，按照日期进行分类,oss会自动帮我们创建对象
        ossClient.putObject(BucketName, pathName, inputStream);

       // 关闭OSSClient。
        ossClient.shutdown();
        //将文件上传的路径返回 https://edu-741.oss-cn-beijing.aliyuncs.com/favicon.ico
        String urlRsult="https://"+BucketName+"."+endpoint+"/"+pathName;
        return urlRsult;
    }


}
